package spring.mvc.web.test.interceptors;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import spring.mvc.web.test.constants.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录验证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * Controller 方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request
            , HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");

        //获取session
        HttpSession session = request.getSession();
        //判断session是否包含用户信息
        if (null == session || null == session.getAttribute(Constants.SESSION_KEY_LOGIN_USER)) {
            //用户未登录
            throw new RuntimeException("用户未登录");
        }
        //用户已登录
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request
            , HttpServletResponse response, Object handler
            , ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");


    }

    @Override
    public void afterCompletion(HttpServletRequest request
            , HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
